import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

# 腐蚀与膨胀
img1 = cv.imread("image/letter.png")
plt.imshow(img1[:, :, ::-1])
plt.show()

# 创建核结构
kenel1 = np.ones((5, 5), np.uint8)

# 腐蚀
img2 = cv.erode(img1, kenel1)
plt.imshow(img2[:, :, ::-1])
plt.show()

# 膨胀
img3 = cv.dilate(img1, kenel1)
plt.imshow(img3[:, :, ::-1])
plt.show()


# 创建核
kenel2 = np.ones((10, 10), np.uint8)
# 开运算(先腐蚀后膨胀)(用于消除结构外的噪点)
open = cv.imread("image/letteropen.png")
plt.imshow(open[:, :, ::-1])
plt.show()

cvopen = cv.morphologyEx(open, cv.MORPH_OPEN, kenel2)
plt.imshow(cvopen[:, :, ::-1])
plt.show()


# 闭运算(先膨胀后腐蚀)(用于消除结构内孔洞)
close = cv.imread("image/letterclose.png")
plt.imshow(close[:, :, ::-1])
plt.show()

cvclose = cv.morphologyEx(close, cv.MORPH_CLOSE, kenel2)
plt.imshow(cvclose[:, :, ::-1])
plt.show()

# 礼帽运算(原图与开运算的结果图之差)
top = cv.morphologyEx(open, cv.MORPH_TOPHAT, kenel2)
plt.imshow(top[:, :, ::-1])
plt.show()

# 黑帽运算(闭运算的结果图与原图之差)
black = cv.morphologyEx(close, cv.MORPH_BLACKHAT, kenel2)
plt.imshow(black[:, :, ::-1])
plt.show()